﻿#define FixBlogEngine
using System;
using System.Linq;
using System.IO;
using System.Xml.Serialization;

namespace N2.BlogEngine.Providers
{
	using global::BlogEngine.Core.DataStore;
	using global::BlogEngine.Core.Providers;
	using N2BlogService = N2.BlogEngine.BlogService;

	public partial class N2BlogProvider : BlogProvider
	{
		public override object LoadFromDataStore(ExtensionType exType, string exId)
		{
			var _result = N2BlogService.CurrentBlog.Storage[exId];

			if (null != _result) {
#if FixBlogEngine
				if (exType == ExtensionType.Widget && this.Name == "XmlBlogProvider") {
					var _bytes = (_result as string)
						.ToCharArray()
						.Select(_ch => (byte)_ch)
						.ToArray();
					
					return new MemoryStream(_bytes);
				}
#endif
			} else if (this.UseFallBackProvider) {
				_result = FallBackProvider.LoadFromDataStore(exType, exId);
				
				if(null != _result) {
					this.SaveToDataStore(exType, exId, _result);
				}
			}

			return _result;
		}

		public override void SaveToDataStore(ExtensionType exType, string exId, object settings)
		{
			string _value;

			var _stream = settings as Stream;
			if (null != _stream) {
				_value = new StreamReader(_stream).ReadToEnd();
				
				if (_stream.CanSeek) {
					_stream.Seek(0, SeekOrigin.Begin);
				}
			} else {
				var _serializer = new XmlSerializer(settings.GetType());
				using (var _writer = new StringWriter()) {
					_serializer.Serialize(_writer, settings);
					_value = _writer.ToString();
				}
			}

			N2BlogService.CurrentBlog.Storage[exId] = _value;
			Context.Persister.Save(N2BlogService.CurrentBlog);
		}

		public override void RemoveFromDataStore(ExtensionType exType, string exId)
		{
			N2BlogService.CurrentBlog.Storage.Remove(exId);
		}

		public override string StorageLocation()
		{
			return this.UseFallBackProvider
				? FallBackProvider.StorageLocation()
				: N2BlogService.EditSection.UploadFolders[0].Path;
		}
	}
}
